<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Layout\Content;
use App\Models\ChinaArea;
use App\Admin\Actions\Access;
use Encore\Admin\Controllers\UserController as BaseUserController;

class UserController extends BaseUserController
{
    protected $access=false;

    public function update($id)
    {
        $this->autorole();
		return $this->form()->update($id);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return mixed
     */
    public function store()
    {
        $this->autorole();
		return $this->form()->store();
    }

	protected function autorole()
	{
			if(request('backend') && request()->has('roles')){	
				$backend = request('backend');
				$roles = request('roles',[]);
				$backends = get_backends();			
				$roleTable = config('admin.database.roles_table');
				$backroles = \DB::table($roleTable)->whereIn('slug',array_keys($backends))->pluck('id', 'slug')->toArray();
				if($backroles['user'] && !in_array($backroles['user'],$roles)){
					array_unshift($roles,$backroles['user']);
				}
				if( $backend!='user' && isset($backroles[$backend])  && !in_array($backroles[$backend],$roles)){
					array_unshift($roles,$backroles[$backend]);
				}
				request()->merge(['roles' => $roles]);
			}
	}

    protected function grid()
    {

		$userModel = config('admin.database.users_model');

        $grid = new Grid(new $userModel());

        $backend = request('backend','');
        if($backend) $grid->model()->where('backend',$backend);
        $grid->column('id', 'ID')->sortable();
        $grid->column('username', trans('admin.username'));
        $grid->column('name', trans('admin.name'));
        $grid->column('email', trans('email'));
        $grid->column('mobile', '手机');
        $grid->column('roles', trans('admin.roles'))->pluck('name')->label();
        $grid->column('created_at', trans('admin.created_at'));
        $grid->column('backend', '后台菜单')->label('info');

        $grid->actions(function ($actions) {
            if ($actions->getKey() == 1) {
                $actions->disableDelete();
            }
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });

		$grid->header(function () use($backend){
            $backends = get_backends();
            $sel='';
            foreach($backends as $k=>$v){
                    $selected =  ($k==$backend) ? "selected" : "";
                    $sel .= "<option value='{$k}' {$selected}>{$v}</option>";
            }
            $str ='<div class="row">
                    <div class="col-md-6" style="margin-left:30px;">
                        <div class="input-group input-group-sm">
                            <div class="input-group-addon btn btn-primary"><i class="fa fa-list"></i> 后台菜单选择</div>
                            <select name="backend" onchange="window.location.href=\'?backend=\'+this.options[this.options.selectedIndex].value"  class="form-control">
                            <option value="">全部</option>'.$sel.'
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                    </div>
                </div>';
            return $str;
        });
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $userModel = config('admin.database.users_model');
        $roleModel = config('admin.database.roles_model'); 
        $permissionModel = config('admin.database.permissions_model');

        $form = new Form(new $userModel());

        $userTable = config('admin.database.users_table');
        $connection = config('admin.database.connection');

        if($this->access)
        {
            //$form->display('id', 'ID');
            $form->display('username', trans('admin.username'));
            $form->display('name', __('admin.name'));        
            $form->display('backend', '后台菜单');
            $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::all()->pluck('name', 'id'));$form->multipleSelect('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'));
            $form->hidden('created_at');
            return $form;            
        }


        $form->tab('基本信息', function (Form $form) use($connection,$userTable,$roleModel,$permissionModel){
            $form->display('id', 'ID');
            $form->text('username', trans('admin.username'))
                ->creationRules(['required', "unique:{$connection}.{$userTable}"])
                ->updateRules(['required', "unique:{$connection}.{$userTable},username,{{id}}"]);
            $form->text('name', __('admin.name'))
                ->creationRules(['required', "unique:{$connection}.{$userTable}"])
                ->updateRules(['required', "unique:{$connection}.{$userTable},name,{{id}}"]);
            $form->email('email', 'Email')
                ->creationRules(['email',"nullable", "unique:{$connection}.{$userTable}"])
                ->updateRules(['email', "nullable","unique:{$connection}.{$userTable},email,{{id}}"]);
            $form->mobile('mobile', '手机')
                ->creationRules([ "nullable","unique:users"])
                ->updateRules([ "nullable","unique:{$connection}.{$userTable},mobile,{{id}}"]);
            $form->image('avatar', trans('admin.avatar'))->move('avatar/'.date('Y-m-d'));
            $form->password('password', trans('admin.password'))->rules('required|confirmed');
            $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
                ->default(function ($form) {
                    return $form->model()->password;
                });

            $form->select('backend','后台菜单')->options(function(){
                    $backends = get_backends();
                    return $backends;
                })->required();
            $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::all()->pluck('name', 'id'));
            $form->multipleSelect('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'));

            $form->display('created_at', trans('admin.created_at'));
            $form->display('updated_at', trans('admin.updated_at'));
        })->tab('附加信息', function (Form $form) {
			$form->radio('profile.gender','性别')->options(['f' => '女', 'm' => '男']);
            $form->date('profile.birthday','生日');


            $form->select('profile.province_id','省份')->options(
                ChinaArea::province()->pluck('name', 'id')
            )
                ->load('profile.city_id', admin_base_path('api/china/city'));
                //->load('test',admin_base_path('api/china/city'));

            $form->select('profile.city_id','城市')->options(function ($id) {
                return ChinaArea::options($id);
            })->load('profile.district_id', admin_base_path('api/china/district'));

            $form->select('profile.district_id','地区')->options(function ($id) {
                return ChinaArea::options($id);
            });

            $form->text('profile.address','地址');
			$form->url('profile.homepage','主页');
            $form->ip('profile.last_login_ip','IP');
            $form->datetime('profile.last_login_at','登录日期');
            $form->textarea('profile.document','签名');
        })->tab('社会化', function (Form $form) {
            $form->text('sns.qq');
            $form->text('sns.wechat');
            $form->text('sns.weibo');
            $form->text('sns.github');
            $form->text('sns.google');
            $form->text('sns.facebook');
            $form->text('sns.twitter');
        });


        $form->ignore(['password_confirmation']);        
        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });

        return $form;
    }


    public function detail($id)
    {
        $userModel = config('admin.database.users_model');
        $show = new Show($userModel::findOrFail($id));
		$show->username('用户名');
        $show->name('呢称');
        $show->avatar('头像')->image();
        $show->email('邮箱');
		$show->mobile('手机');
        $show->divider();

        $show->created_at('注册日期');
        $show->updated_at('更新日期');

        $show->profile('扩展',function ($profile) {
			
            $profile->province('省份')->as(function(){
				$id = $this->attributes['province_id']??'';
				if($id){
					$area = ChinaArea::province()->find($id);
					if(!empty($area)) return $area->name;
				}
				return '';
			});
            $profile->city('城市')->as(function(){
				$id = $this->attributes['city_id']??'';
				if($id){
					$area = ChinaArea::city()->find($id);
					if(!empty($area)) return $area->name;
				}
				return '';
			});
            $profile->district('地区')->as(function(){
				$id = $this->attributes['district_id']??'';
				if($id){
					$area = ChinaArea::district()->find($id);
					if(!empty($area)) return $area->name;
				}
				return '';
			});
            $profile->address('地址');
            $profile->homepage('主页')->link();
            $profile->gender('性别')->using(['f' => '女', 'm' => '男']);
            $profile->birthday('生日');
            $profile->address('地址');
            $profile->document('签名');
            $profile->last_login_at('最后登录');
            $profile->last_login_ip('登录IP');

        });

        $show->sns(function ($sns) {
            $sns->qq();
            $sns->wechat();
            $sns->weibo();
            $sns->github();
            $sns->google();
            $sns->facebook();
            $sns->twitter();

        });
/*
        $show->friends(function ($friend) {
            $friend->resource('users');
            $friend->name();
            $friend->email();
        });
*/
        return $show;
    }

}
